package com.second.app.huaweiod;


/**
 * 字符串中 回文数最大长度
 *
 * 解法1
 */
public class HuiwenDemo {

    public static void main(String args[]) {
        HuiwenDemo demo = new HuiwenDemo();
        String str = demo.longestPalindrome("babad");
        System.out.println("str: "+str);
    }

    public String longestPalindrome(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        int start = 0, end = 0;

        for (int i = 0; i < s.length(); i++) {
            int len1 = expand(s, i, i);     // 奇数回文
            int len2 = expand(s, i, i + 1); // 偶数回文
            int len = Math.max(len1, len2);

            if (len > end - start + 1) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }

        return s.substring(start, end + 1);
    }

    private int expand(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1; // 扩散后越界，因此长度是差 -1
    }
}
